//
//  WBDataListViewModel.swift
//  WB
//
//  Created by macssss on 16/7/2.
//  Copyright © 2016年 macssss. All rights reserved.
//

import Foundation
import SDWebImage

/// 上拉刷新最大尝试次数
private let maxPullupTryTimes = 3

class WBDataListViewModel {
    
    //懒加载 创建模型数组
    lazy var statusList = [WBStatusViewModel]()

    /// 上拉刷新错误次数
    private var pullupErrorTimes = 0


    //数组转模型
    func loadStatus(pullup: Bool, completion:(isSuccess: Bool, shouldRefresh: Bool)->()) {

        // 判断是否是上拉刷新，同时检查刷新错误
        if pullup && pullupErrorTimes > maxPullupTryTimes {
            
            completion(isSuccess: true, shouldRefresh: false)
            
            return
        }

        let since_id = pullup ? 0 : (statusList.first?.status.id ?? 0)
        
        //判断是否是下上刷新
        let max_id = !pullup ? 0 : (statusList.last?.status.id ?? 0)
        
        WBNetworkManager.shared.statusList(since_id: since_id, max_id: max_id) { (List, isSuccess) in
            
            //判断网络请求是否成功
            if !isSuccess {
                
                completion(isSuccess: false, shouldRefresh: false)
                
                return
            }
            
            var array = [WBStatusViewModel]()
            
            //遍历网络返回的数组 字典转模型
            
            // 1> 创建微博模型
            

            for dict in List ?? [] {
                  //print(dict["pic_urls"])
                
                let status = WBDataModel()
                
                status.yy_modelSet(with: dict)
                
                let viewModel = WBStatusViewModel(model: status)
                
                array.append(viewModel)
            }

            print("刷新到 \(array.count) 条数据 \(array)")

            if pullup {
                
                //上拉刷新
                self.statusList += array
            } else {
                
                //拼接数组 下拉刷新
                self.statusList = array + self.statusList
   
            }
            
            if pullup && array.count == 0 {
                
                
                self.pullupErrorTimes += 1
                
                completion(isSuccess: isSuccess, shouldRefresh: false)
            } else {
                
                self.catheSingleImage(List: array, finished: completion)
                
            //完成回调
            completion(isSuccess: isSuccess, shouldRefresh: true)
            
            }
        }
    }
    
    //缓存单张图像
    private func catheSingleImage(List: [WBStatusViewModel], finished:(isSuccess: Bool, shouldRefresh: Bool)->()) {
        
        //调度组
        let group = DispatchGroup()
        
        //记录长度
        var length = 0
        
        
        for vm in List {
            
          if vm.picUrls?.count != 1 {
            
                continue
            }
            guard let pic = vm.picUrls?[0].thumbnail_pic,
                let url = URL(string: pic) else {
                continue
            }
            
            print("要缓存的url是\(url)")
            
            //入组
            group.enter()
            SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (image,_, _, _, _) in
                
                if let image = image,
                    data = UIImagePNGRepresentation(image) {
                    
                    length += data.count
                    vm.updataSingleImageSize(image: image)
                }
                
                //出组
                group.leave()
                print("缓存的图像是\(image)长度是\(length)")
            })
        }
        
        group.notify(queue: DispatchQueue.main) { 
            
            print("图像缓存完成\(length/1000) K")
            
            finished(isSuccess: true, shouldRefresh: true)
        }
    }

   
}























